<template>
  <el-upload v-model:file-list="fileList"
             class="upload-demo"
             style="width: 300px;height: 130px"
             drag
             :http-request="uploadFiles"
             limit="1"
             :accept="props.fileType!==''?props.fileType:fileType"
             multiple
             :on-progress="handleAvatarSuccess"
             :on-remove="handleRemove"
             :on-change="handChanges">
    <el-icon class="el-icon--upload">
      <upload-filled/>
    </el-icon>
    <div class="el-upload__text">
      选择文件或 <em>拖拽上传</em>
      <div style="color: silver;" v-if="props.fileType!==''">上传{{props.fileType.split(',')[0]}}和 {{props.fileType.split(',')[1]}}文档</div>
    </div>
  </el-upload>
</template>
<script lang="ts" setup>
import {ref} from 'vue'
import {UploadFilled} from '@element-plus/icons-vue'
import type {UploadProps, UploadUserFile} from 'element-plus'
import {ElMessage} from "element-plus";
import {getRandomString, removeFile, uploadFileMerge, uploadFileSave,} from "@/api/fileApi.js";
import * as pdfjsLib from "pdfjs-dist";
import * as mammoth from "mammoth";

const props = defineProps({
  limit: {
    type: Number,
    default: 1
  },
  fileType: {
    type: String,
    default: ''
  },
  fileName: {
    type: String,
    default: ''
  },
  isToHtml: {
    type: Boolean,
    default: false
  }
})
const fileType= '.zip,.7z,.tar,.wim,.xz,.gzip,.bzip2,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.pdf,.txt'
const dialogImageUrl = ref('')
const emit = defineEmits(['handleFileSuccess','handleHtmlContent'])
const fileList = ref<UploadUserFile[]>([])

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  removeFile(uploadFile.raw.name).then(res => {
    if (res.data.code === 0) {
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
  });
}
const handleAvatarSuccess = () => {

}
const uploadFiles = async (options) => {
}
const handChanges = async (file, fileList) => {
  const {name, size, raw: uploadFile} = file;
  //随机生成guid
  let guid = getRandomString(30); //随机生成guid
  let index = 0; //默认分片
  // 分片上传
  let chunkSize = 5 * 1024 * 1024; //每一个分片为5M
  let start = chunkSize * index;
  let dir = '';//临时目录名
  while (start < size) {
    let blob = null;
    if (start + chunkSize > size) {
      blob = uploadFile.slice(start, size)
    } else {
      blob = uploadFile.slice(start, start + chunkSize)
    }
    start += chunkSize; //分片累加
    //分片上传
    let boltFile = new File([blob], name);
    let formData = new FormData;
    formData.append('file', boltFile)
    formData.append('chunk', index.toString())
    formData.append('guid', guid)
    let res = await uploadFileSave(formData);
    dir = res.data
    index += 1;
  }
  //合并
  let extList = name.split(".")
  let ext = extList[extList.length - 1];
  let formData1 = new FormData;
  formData1.append("guid", guid);
  formData1.append("fileName", name);
  let res = await uploadFileMerge(formData1);
  // 更新fileList
  fileList.value = [
    {
      name: name,
      url: res.data, // 假设res.data是上传成功后的图片地址
    }]
  emit('handleFileSuccess', res.data)
  if (props.isToHtml){
    convertFileToHtml(uploadFile)
  }
}

// 初始化 pdfjsLib 的 worker 路径
pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`;
const convertFileToHtml = async (file) => {
  const fileType = file.type;
  const fileExtension = file.name.substring(file.name.lastIndexOf("."));
  // 将文件转换为Blob对象
  const fileReader = new FileReader();
  fileReader.onload = async (event) => {
    const arrayBuffer = event.target.result;
    if (fileType === 'application/pdf') {
      // 使用pdfjsLib将PDF转换为HTML
      const pdfData = await pdfjsLib.getDocument(arrayBuffer).promise;
      const pageNumber = 1;
      const scale = 1.5;
      const page = await pdfData.getPage(pageNumber);
      const viewport = page.getViewport({ scale: scale });
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      canvas.width = viewport.width;
      canvas.height = viewport.height;
      const renderContext = {
        canvasContext: context,
        viewport: viewport,
      };
      await page.render(renderContext).promise;
      const base64Image = canvas.toDataURL('image/png');
      // 将base64Image转换为HTML
      const htmlContentStr = `<img src="${base64Image}" />`;
      emit('handleHtmlContent', htmlContentStr)
    }
    else if (fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
      // 使用mammoth将Word转换为HTML
      const result = await mammoth.convertToHtml({ arrayBuffer: arrayBuffer })
          .catch(error => {
            console.error("转换文件时出错: ", error);
            ElMessage.error("文件转换失败，请检查文件格式");
            return;
          });
      if (!result) return; // 如果转换失败，提前返回
      emit('handleHtmlContent', result.value)
    }
  };
  fileReader.readAsArrayBuffer(file); // 在 onload 外部调用
}



</script>
<style setup>
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.search-title {
  background: white;
  padding: 10px;
  margin-top: 10px;
}


.demo-pagination-block {
  margin-top: 10px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  text-align: center;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatarImage {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
